package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CustomerServiceImpl
 * @Author 波
 * @Date 2024/9/24 14:20
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDao customerDao;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String customerName) {
        Map<String, Object> map = new HashMap<>();
        page = page == 0 ? 1 : page;
        int offset = (page - 1) * rows;
        try {
            List<Customer> customers = customerDao.list(offset, rows, customerName);
            int count = customerDao.getCount(customerName);
            map.put("rows", customers);
            map.put("total", count);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public void save(Customer customer) {
        Integer customerId = customer.getCustomerId();
        String customerName = customer.getCustomerName();
        String contacts = customer.getContacts();
        String phoneNumber = customer.getPhoneNumber();
        String address = customer.getAddress();
        String remarks = customer.getRemarks();
        if (customerId == null) {
            int result = customerDao.save(customerName, contacts, phoneNumber, address, remarks);
            if (result == 0) {
                throw new RuntimeException("添加客户信息失败");
            }
        } else {
            int result = customerDao.update(customerId, customerName, contacts, phoneNumber, address, remarks);
            if (result == 0) {
                throw new RuntimeException("修改客户信息失败");
            }
        }


    }

    @Override
    public void delete(String ids) {
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            int result = customerDao.delete(Integer.parseInt(id));
            if(result==0){
                throw new RuntimeException("删除客户信息失败");
            }
        }

    }
}
